package utils

import (
	"context"
	"strconv"
	"time"

	"gitee.com/yanwc/gozero-utils/errx"
	redis "github.com/redis/go-redis/v9"
)

func GenerateNo(ctx context.Context, client *redis.Client, prefix string) (string, *errx.Error) {
	v := time.Now().Unix()
	key := prefix + strconv.Itoa(int(v))

	intCmd := client.Incr(ctx, key)
	if intCmd.Err() != nil {
		return "", errx.New(errx.CACHE_ERROR, errx.WithMsgOption(intCmd.Err().Error()), errx.WithErrorOption(intCmd.Err()))
	}

	boolCmd := client.Expire(ctx, key, 2*time.Second)
	if boolCmd.Err() != nil {
		return "", errx.New(errx.CACHE_ERROR, errx.WithErrorOption(boolCmd.Err()), errx.WithMsgOption(boolCmd.Err().Error()))
	}

	incr, err := intCmd.Result()
	if err != nil {
		return "", errx.New(errx.CACHE_ERROR, errx.WithErrorOption(boolCmd.Err()), errx.WithMsgOption(boolCmd.Err().Error()))
	}
	no := v + incr
	return prefix + strconv.Itoa(int(no)), nil
}
